package com.datapermission.aspect;

import com.datapermission.annotation.Permission;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionAspect {

    private static final Logger log = LoggerFactory.getLogger(PermissionAspect.class);

    @Pointcut("@annotation(com.datapermission.annotation.Permission)")
    public void permissionPointcut() {
    }

    @Around("permissionPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Permission deptPermission = method.getAnnotation(Permission.class);
        // 将注解信息存储到ThreadLocal
        PermissionContext.set(deptPermission);
        try {
            return joinPoint.proceed();
        } finally {
            // 清除ThreadLocal中的信息
            PermissionContext.clear();
            log.warn("调用PermissionContext.clear()");
        }
    }
}